package com;

import com.handler.inbound.MetaInfoDecoder;
import com.handler.inbound.SkipOffsetUploader;
import com.handler.outbound.MetaInfoEncoder;
import com.to.MetaInfo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LoggingHandler;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.TimeUnit;

public class Client {

    static NioSocketChannel channel;

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup(2))
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {


                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
//                                new LoggingHandler(),
                                new LengthFieldPrepender(2, 0, false),


                                /*new MessageToByteEncoder<Object>() {
                                    @Override
                                    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
                                        String str = msg.toString();

                                        out.writeBytes(str.getBytes(StandardCharsets.UTF_8));
                                    }
                                },*/
                                new MetaInfoEncoder(),
                                new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2),

                                new MetaInfoDecoder(),
                                new SkipOffsetUploader()


                        );

                    }
                }).connect("localhost", 38888);
        channelFuture.get();

        if (channelFuture.isSuccess()) {
            System.out.println("连接服务器成功！");
        }
        String inputFilePath = "/Users/luojun/Downloads/Microsoft_Office_16.61.22050700_Installer.pkg";
        for (int i = 0; i < 1; i++) {

            MetaInfo build = MetaInfo.builder()
                    .inputFilePath(inputFilePath)
                    .path("/Users/luojun/temp/html/")
                    .fileName(inputFilePath.substring(inputFilePath.lastIndexOf("/")+1))
                    .appendFile(false)
                    .build();

            channelFuture.channel().write(build);
        }

        channelFuture.channel().flush();
        TimeUnit.HOURS.sleep(1);
    }
}
